package cn.cloudplug.ui.delegate.spinner;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatSpinner;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.cloudplug.core.delegate.ScentDelegate;
import cn.cloudplug.ui.R;
import cn.cloudplug.ui.R2;

/**
 * Created by pc on 2018/1/23.
 */

public abstract class SpinnerBaseDelegate extends ScentDelegate implements AdapterView.OnItemSelectedListener {

    @BindView(R2.id.spinner)
    AppCompatSpinner spinnerBar;

    @BindView(R2.id.toolGroup)
    RelativeLayout toolGroup;

    @OnClick(R2.id.iv_back)
    public void clickBack(){
        getSupportDelegate().pop();
    }

    private final ArrayList<String> titles = new ArrayList<>();
    private final ArrayList<ScentDelegate> ITEM_DELEGATES = new ArrayList<>();
    private final LinkedHashMap<String, ScentDelegate> ITEMS = new LinkedHashMap<>();
    private int mCurrentDelegate = 0;
    private int mIndexDelegate = 0;
    private ArrayAdapter<String> adapter;
    private boolean tag=true;
    private boolean adapterTag=true;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void addBean(String text, ScentDelegate delegate){
        ITEMS.put(text,delegate);
        titles.add(text);
        ITEM_DELEGATES.add(delegate);
        adapter = new ArrayAdapter<String>(getContext(),R.layout.spinner_text,titles);
        if (spinnerBar!=null)spinnerBar.setAdapter(adapter);
        if (tag){
            getSupportDelegate().loadRootFragment(R.id.content, ITEM_DELEGATES.get(mIndexDelegate));
            tag=false;
        }
    }

    public abstract void addViewToToolbar(RelativeLayout group);

    @Override
    protected Object setContent() {
        return R.layout.delegate_spinner;
    }

    @Override
    protected void onBindView(Bundle savedInstanceState, View view) {
        addViewToToolbar(toolGroup);
        spinnerBar.setSelection(0, true);
        spinnerBar.setOnItemSelectedListener(this);

    }



    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if(!adapterTag){
            ITEM_DELEGATES.get(mCurrentDelegate).getSupportDelegate().replaceFragment(ITEM_DELEGATES.get(position), false);
            mCurrentDelegate=position;
        }else{
            adapterTag=false;
        }

    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
